package com.eternal.base.exception;

import android.Manifest;
import androidx.fragment.app.FragmentActivity;

import com.eternal.base.data.ble.BleServer;
import com.eternal.framework.component.AppManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * Created by Administrator
 * On 2020/4/24
 * Description:
 * @author Administrator
 */
public class ExceptionHandle {

    public static <T> ObservableTransformer<T, T> handle(){
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) throws Exception {
                        return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
                            @Override
                            public ObservableSource<?> apply(final Throwable throwable) throws Exception {
                                if(throwable instanceof NotEnableBluetoothException){
                                    return new RxPermissions((FragmentActivity) AppManager.getAppManager().currentActivity())
                                            .request(Manifest.permission.BLUETOOTH,
                                                    Manifest.permission.ACCESS_FINE_LOCATION)
                                            .map(new Function<Boolean, Observable>() {
                                                @Override
                                                public Observable apply(Boolean aBoolean) {
                                                    if(aBoolean){
                                                        BleServer.getInstance().enable();
                                                        return Observable.empty();
                                                    }
                                                    return Observable.error(throwable);
                                                }
                                            });
                                }else{
                                    return Observable.error(throwable);
                                }
                            }
                        });
                    }
                });
            }
        };
    }
}
